<?php

/**
 * BannerForm class.
 * BannerForm is the data structure for keeping
 * web Ad form data. It is used by the 'banner' action of 'BannerController'.
 */
class BannerForm extends Banner
{
    public $sign;
    public $img;
    public $target = Constants::TARGET_BLANK;
    public $link;
    public $sort = 0;
    public $status = Constants::Status_Enable;
    public $desc;

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
            array('sort, status', 'numerical', 'integerOnly'=>true, 'min'=>0),
			array('id,value,sign,target,link,desc,img','safe'),
			//array('ad', 'file', 'types' => array('png', 'jpg', 'jpeg', 'gif', 'webp')),
			// 验证字符串 string
			//array('website_title, website_email, website_language, website_icp, website_statics_script, website_timezone, website_url, seo_title, seo_keywords, seo_description', 'boolean'),
			//array('smtp_port', 'numerical', 'integerOnly'=>true, 'min'=>0, 'max'=>65535),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
            'name' => Yii::t('app', '名称'),
            'input_type' => Yii::t('app', 'Ad Type'),
            'tips' => Yii::t('app', '描述'),
            'ad' => Yii::t('app', '广告类容'),
            'link' => Yii::t('app', 'Jump Link'),
            'desc' => Yii::t('app', 'Ad Explain'),
            'autoload' => Yii::t('app', 'Status'),
            'sort' => Yii::t('app', 'Sort'),
            'target' => Yii::t('app', 'Target'),
            'status' => Yii::t('app', '状态'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
		);
	}

    public function beforeDelete()
    {
        if( !empty($this->value) ) {
            $this->addError("id", Yii::t('app', 'Delete failed, banner existed'));
            return false;
        }
        return parent::beforeDelete();
    }

    public static function getBanners($id, $asArray=false)
    {
        $model = parent::model()->find('id=:id AND type=:type',array(':id'=>$id, ':type'=>self::TYPE_BANNER));
        if( $model == '' ) throw new HttpException("Cannot find id $id");
        $models = [];
        if(is_array($model->value)){
            foreach ($model->value as $banner){
                $temp = [
                    'id' => $id,
                    'sign' => $banner['sign'],
                    'img' => $banner['img'],
                    'target' => $banner['target'],
                    'desc' => $banner['desc'],
                    'link' => $banner['link'],
                    'sort' => $banner['sort'],
                    'status' => $banner['status'],
                ];
                $models[$banner['sign']] = $asArray ? $temp : new self($temp);
            }
        }
        return $models;
    }



}
